module(...,package.seeall)

import "java.io.DataOutputStream"
import "java.io.InputStreamReader"
import "android.content.Context"
--local WADB={}
function getPort()
  return tonumber(exec("getprop service.adb.tcp.port"))
  --[[
  local result
  xpcall(function()
    local proc = Runtime.getRuntime().exec("su")
    local dos = DataOutputStream(proc.getOutputStream())
    dos.writeBytes("getprop service.adb.tcp.port\n")
    dos.flush()
    dos.close()
    local reader=InputStreamReader(proc.getInputStream())
    local chars=char[5]
    reader.read(chars)
    reader.close()
    proc.destroy()
    result=String(chars)
  end,function()
    result="5555"
  end)
  return result]]
end
function isActivated()
  local port=getPort()
  return toboolean(port and port~=-1)
  --[[
  local result
  local strings=getPort()
  result=strings.matches("[0-9]+\\n") && !strings.contains("-1")
  return result]]
end
function getIpAddress(context)
  local wm=context.getApplicationContext().getSystemService(Context.WIFI_SERVICE)
  if wm then
    local i=wm.getConnectionInfo().getIpAddress()
    return tostring(String.format(Locale.getDefault(), "%d.%d.%d.%d",{i & 0xFF, (i >> 8) & 0xFF, (i >> 16) & 0xFF, (i >> 24) & 0xFF}))
   else
    return "0.0.0.0"
  end
end
function setWadbState(port)
  local portSucceed=os.suexecute("setprop service.adb.tcp.port "..tostring(port))
  local stopSucceed=os.suexecute("stop adbd")
  local startSucceed=os.suexecute("start adbd")
  return portSucceed and stopSucceed and startSucceed
end
--return WADB